package com.jqr.activity.guessing

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.FragmentActivity
import androidx.navigation.findNavController
import com.jqr.activity.guessing.databinding.FragmentGuessingBinding


/**
 * A simple [Fragment] subclass.
 * Use the [GuessingFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class GuessingFragment : Fragment(){
    private  var _binding:FragmentGuessingBinding?=null
    private val binding get() = _binding!!
    val words= listOf("Android","Activity","Fragment")
    val secretWords=words.random().uppercase()
    var secretWordDisplay=""
    var correctGuesses=""
    var inCorrectGuesses=""
    var liveLeft=9
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        _binding=FragmentGuessingBinding.inflate(layoutInflater,container,false)
        val view=binding.root
        secretWordDisplay=deliverSecretWordDisplay()
        updateScreent()
        binding.btnGuess.setOnClickListener{
            makeGuess(binding.guess.text.toString().uppercase())
            binding.tvWord.text=""
            updateScreent()
            if(isLost()||win()){
                var action=GuessingFragmentDirections.actionGuessingFragmentToResultFragment(lossMessage())
                view.findNavController().navigate(action)
            }

        }


        return  view
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding=null
    }

    fun  makeGuess(guess:String){
        if(guess.length==1){
            if(secretWords.contains(guess)){
                System.out.println(guess)
                correctGuesses+=guess
                secretWordDisplay=deliverSecretWordDisplay()
            }
            else{
                inCorrectGuesses+="$guess"
                liveLeft--
            }
        }

    }

    private fun deliverSecretWordDisplay(): String {
        var display=""
        secretWords.forEach {
            display+=checkLetter(it.toString());
        }
        return  display
    }

    private fun checkLetter(str: String) =
        when(correctGuesses.contains(str)){
            true -> str
            false -> "_"
        }



    fun  updateScreent(){
        binding.tvWord.text=secretWordDisplay
        binding.tvLives.text="还剩 $liveLeft 次机会"
        binding.tvCorrectGuesses.text="猜错的字母是：$inCorrectGuesses"
    }

    fun  win()=secretWords.equals(secretWordDisplay,true)
    fun  isLost()=liveLeft<=0

    fun lossMessage():String{
        var message=""
        if(win()){
            message="祝贺你，猜对了";
        }
        else if(isLost()){
            message="你失败了，继续加油！"
            message+="该单词为 $secretWords"
        }

        return message;

    }
}